'use strict';

angular.module('metalabPartnerApp').controller('TalentSearchCtrl', ['$scope', '$stateParams', 'MetaResources', '$state', '$location', '$anchorScroll', '$uibModal', 'MetaSEO', 'MetaRemind', 'MetaConstants',
    function ($scope, $stateParams, resource, $state, $location, $anchorScroll, $uibModal, MetaSEO, MetaRemind, constants) {
        ///--初始化
        ///**搜索关键字
        $scope.searchText = $stateParams.keywords;//输入关键字
        $scope.keywords = $stateParams.keywords;//关键字参数

        $scope.waiting = true;//等候搜索标志

        var achievements = [];//保存网站资源数据--来自搜索引擎
        var solrData;//保存搜索引擎的资源数据--来自搜索引擎

        ///**筛选
        $scope.filters = {
            'districts': {
                'datas': constants.provinces,
                'items': []
            },
            'times': {
                'datas': ['不限', '近三年', '近五年', '近十年'],
                'item': '不限'
            },
            'types': {
                'datas': [{
                    '一级数据': '国家重大专项等高新科技',
                    '二级数据': '专利及发明'
                }, {}],
                'item': '二级数据'
            },
            go: function () {
                getData();
            }
        };


        $scope.tab = [{//初始化tab
            title: '>>专家详情',
            active: false,
            disabled: false,
            show: false,
            Select: function () {//tab选择，默认选择列表第一项
                $scope.tab[0].active = true;
                if ($scope.page.pageIndex === -1) $scope.page.pageIndex = 0;
                $scope.page.data[$scope.page.pageIndex === -1 ? 0 : $scope.page.pageIndex] ? ($scope.page.data[$scope.page.pageIndex === -1 ? 0 : $scope.page.pageIndex]) : '';
            },
        }, {
            title: '相关技术资源',
            active: true,
            disabled: false,
            Select: function () {//tab选择
                $scope.page.pageIndex = -1;
                $scope.tab[0].show = false;
            }
        }];
        ///**数据模型：存放专家详情
        $scope.talent = {
            talentInfo: {},
            achievements: []
        };

        ///**数据模板:存放成果资源
        $scope.achievementSet = {
            all: [],
            data: [],
            currentPage: 0,
            pageNumber: 10,
            Change: function () {
                $scope.achievementSet.data = $scope.achievementSet.all.slice((this.currentPage - 1) * this.pageNumber, this.currentPage * this.pageNumber);
            }
        };

        ///**数据模板:存放左侧列表
        $scope.page = {
            data: [],//人才列表
            pageIndex: -1,
            /**
             * @function 选择列表项
             * @param i 想要选择的序号（从0开始）
             */
            SelectItem: function (i) {
                this.pageIndex = i;
                $scope.tab[0].show = true;
                $scope.tab[0].Select(i);
                this.data[i] ? searchAchievement(this.data[i]) : '';
            }
        };

        /**
         * @function 根据人才查找资源
         * @param talent
         */
        var searchAchievement = function (talent) {
            $scope.talent.talentInfo = talent;
            $scope.talent.achievements = [];
            if (talent.id) {
                resource.achievement.query({
                    talentId: talent.id,
                    _embed:'talent,talent.user'
                }, function (data) {
                    console.log(data,achievements);
                    for (var i = achievements.length - 1; i >= 0; i--) {//遍历搜索所得资源
                        if (achievements[i].talentId === talent.id) {
                            for (var j = 0; j < data.length; j++) {//遍历该人才的资源
                                if (data[j].id === achievements[i].id) {
                                    console.log(data[j]);
                                    data.splice(j, 1);
                                    data.unshift(achievements[i]);
                                }
                            }
                        }
                    }
                    $scope.talent.achievements = data;
                    // console.log()
                }, function (err) {
                    console.log('err', err);
                });
            } else {
                for (var a in $scope.achievementSet.all) {
                    if ($scope.filters.types.item == '一级数据' && $scope.achievementSet.all[a].author && $scope.achievementSet.all[a].author.indexOf(talent.split('|')[0]) !== -1) {
                        $scope.talent.achievements.push(angular.copy($scope.achievementSet.all[a]));
                    } else if ($scope.filters.types.item == '二级数据' && $scope.achievementSet.all[a].designer && $scope.achievementSet.all[a].designer.indexOf(talent.split('|')[0]) !== -1) {
                        $scope.talent.achievements.push(angular.copy($scope.achievementSet.all[a]));
                    }
                }
            }
        };

        /**
         * @function 实时响应-关键字拆分
         */
        $scope.$watch("searchText", function (newVal, oldVal) {
            if ($stateParams.keywords && $scope.waiting) return;
            newVal ? getSegment(newVal) : '';
        });

        /**
         * @function 获得分词
         * @param val 用于分词的值
         */
        var getSegment = function (val) {
            resource.search.segment({//获得分词结果
                searchText: val
            }, function (result) {
                $scope.keywordList = result;
            }, function () {
                MetaRemind.error('出错了,请稍后再试！');
            });
        };

        /**
         * @function 获取数据
         */
        var getData = function () {
            $scope.waiting = true;
            resource.search.segment({//获得分词结果
                searchText: $stateParams.keywords
            }, function (result) {
                if (result.length < 1) {
                    MetaRemind.error('您输入的搜索词无效，请重新输入');
                    $scope.page.data = [];
                    $scope.waiting = false;
                    return;
                }
                $scope.keywordList = result;
                $scope.waitingListPromise = resource.search.engine({
                    searchArray: $scope.keywordList,
                    searchText: $stateParams.keywords,
                    filterDistrict: $scope.filters.districts.items.length > 0 ? $scope.filters.districts.items : ['不限'],
                    filterTime: $scope.filters.times.item,
                    filterType: $scope.filters.types.item,
                    _embed: 'user,talent,talent.user'
                }, function (result) {
                    solrData = result.solrResult;
                    achievements=result.achievement;
                    $scope.page.data = (typeof result.authorRank) == "object" ? ((typeof result.talent) == "object" ? result.talent.slice(0, 10).concat(result.authorRank) : result.authorRank) : ((typeof result.talent) == "object" ? result.talent.slice(0, 10) : []);
                    // $scope.achievementSet.all = (typeof result.achievement) == "object" ? ((typeof result.solrResult) == "object" ? result.achievement.concat(result.solrResult) : result.achievement) : ((typeof result.solrResult) == "object" ? result.solrResult : []);
                    $scope.achievementSet.all = (typeof result.solrResult) == "object" ? result.solrResult : [];
                    $scope.achievementSet.data = $scope.achievementSet.all.slice(0, $scope.achievementSet.pageNumber);
                    $scope.achievementSet.currentPage = $scope.achievementSet.all.length > 0 ? 1 : 0;
                    $scope.waiting = false;
                    if ($scope.achievementSet.data.length < 1) {
                        $scope.page.SelectItem(0);
                    }
                }, function (err) {
                    $scope.waiting = false;
                    MetaRemind.error('出错了', err);
                }).$promise;
            }, function () {
                MetaRemind.error('出错了,请稍后再试！');
            });
        };

        /**
         * @function 搜索功能
         */
        $scope.search = function () {
            if ($scope.searchText && $scope.searchText.length > 0 && !$scope.waiting) {
                //$scope.tabs[0].active = true;
                //$scope.tabs[1].active = false;
                $state.go('meta.talent.search', {
                    keywords: $scope.searchText,
                    keywordList: $scope.keywordList.length > 0 ? $scope.keywordList.join(',') : undefined
                });
            } else {
                MetaRemind.warn('请输入关键字进行搜索');
            }
        };

        $scope.openDetailModal = function (achievement, keywordList) {
            var modalInstance = $uibModal.open({
                animation: false,
                templateUrl: 'views/talent/template/detailModal.html',
                controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
                    console.log(achievement);
                    $scope.achievement = achievement;
                    // $scope.keywordList = $stateParams.keywordList.split(',');
                    $scope.keywordList = keywordList;
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                }],
                size: 'lg'
            });
            modalInstance.result.then(function () {
                console.log(1);
            }, function () {
                console.log(2);
            });
        };

        (function () {
            getData();
            MetaSEO.setSEO('迈科技搜索-'+$scope.searchText, null, '技术资源,专业技术,资源搜索');
        }());
    }]);
